package cn.jetpiece.cloud.log.app.modular.mq.consumer;

import cn.jetpiece.cloud.log.api.GatewayLogApi;
import cn.jetpiece.cloud.log.api.model.params.GatewayLogParam;
import cn.jetpiece.cloud.log.app.modular.log.service.GatewayLogService;
import cn.jetpiece.cloud.core.context.RequestDataHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class LogConsumer {
    private final GatewayLogService gatewayLogService;
    private final RedisTemplate<String, Object> redisTemplate;
    private static Boolean isRunning = false;

    /**
     * 每分钟一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void getMessage() {
        if (isRunning) {
            return;
        }
        try {
            isRunning = true;
            while (isNotEmpty()) {
                GatewayLogParam param = (GatewayLogParam) redisTemplate.opsForList().rightPop(GatewayLogApi.GATEWAY_LOG_CACHE);
                onMessage(param);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            isRunning = false;
        }
    }

    /**
     * 是否不为空
     */
    private boolean isNotEmpty() {
        Long size = redisTemplate.opsForList().size(GatewayLogApi.GATEWAY_LOG_CACHE);
        return size != null && size > 0;
    }

    public void onMessage(GatewayLogParam gatewayLogParam) {
        RequestDataHolder.put((JSONObject) JSON.toJSON(gatewayLogParam));
        gatewayLogService.add(gatewayLogParam);
    }
}
